/**
 * Mastra集成层
 * 为前端提供统一的AI Agent接口
 */

import { MastraClient } from '@mastra/client-js';

/**
 * Mastra客户端配置
 */
const MASTRA_CONFIG = {
  baseUrl: import.meta.env.VITE_MASTRA_API_URL || 'http://localhost:4111',
  retries: 3,
  backoffMs: 300,
  maxBackoffMs: 5000,
};

/**
 * 创建Mastra客户端实例
 */
export const mastraClient = new MastraClient(MASTRA_CONFIG);

/**
 * 游戏Agent接口类型定义
 */
export interface GameAgentResponse<T = any> {
  success: boolean;
  message: string;
  data?: T;
  gameState?: any;
  sessionInfo?: any;
  nextActions?: string[];
  error?: string;
  agentResponse?: string;
}

/**
 * 游戏配置接口
 */
export interface GameConfig {
  difficulty: 'easy' | 'normal' | 'hard';
  theme?: string;
  suspectCount?: number;
  playerProfile?: {
    name?: string;
    experience?: string;
    preferences?: any;
  };
}

/**
 * 对话请求接口
 */
export interface ChatRequest {
  sessionId: string;
  suspectId: string;
  question: string;
  conversationHistory?: Array<{
    role: 'user' | 'assistant';
    content: string;
    timestamp?: string;
  }>;
}

/**
 * 推理提交接口
 */
export interface DeductionSubmission {
  sessionId: string;
  culpritId: string;
  reasoning: string;
  evidence: string[];
  confidence: number;
}

/**
 * 赛博侦探游戏Agent客户端
 * 提供与后端AI Agent的统一交互接口
 */
export class CyberDetectiveGameClient {
  private client: MastraClient;

  constructor(client: MastraClient = mastraClient) {
    this.client = client;
  }

  /**
   * 开始新游戏
   * 通过游戏主控Agent创建新的游戏会话
   */
  async startNewGame(config: GameConfig): Promise<GameAgentResponse> {
    try {
      console.log('🎮 通过游戏主控Agent开始新游戏:', config);

      const agent = this.client.getAgent('gameMasterAgent');
      const result = await agent.generateVNext({
        messages: [
          {
            role: 'user',
            content: `请开始一个新的赛博侦探游戏。

            游戏配置：
            - 难度：${config.difficulty}
            - 主题：${config.theme || '随机选择'}
            - 嫌疑人数量：${config.suspectCount || 3}
            - 玩家档案：${JSON.stringify(config.playerProfile || {})}

            请使用 game-master 工具执行 start_game 操作，创建完整的游戏会话。`
          }
        ]
      });

      console.log('🤖 游戏主控Agent响应:', result);
      
      // 从工具调用结果中提取游戏数据
      if (result.toolResults && result.toolResults.length > 0) {
        const toolResult = result.toolResults[0];
        if (toolResult.payload?.result) {
          const gameData = toolResult.payload.result;
          return {
            success: gameData.success || true,
            data: gameData.data,
            gameState: gameData.gameState,
            sessionInfo: gameData.sessionInfo,
            nextActions: gameData.nextActions,
            message: gameData.message || '游戏开始成功',
            agentResponse: result.text
          };
        }
      }

      return {
        success: false,
        message: '游戏开始失败：Agent未返回有效结果',
        error: 'NO_TOOL_CALLS',
        agentResponse: result.text
      };

    } catch (error) {
      console.error('❌ 开始新游戏失败:', error);
      return {
        success: false,
        message: `开始游戏失败: ${error instanceof Error ? error.message : '未知错误'}`,
        error: 'CLIENT_ERROR'
      };
    }
  }

  /**
   * 与嫌疑人对话
   * 通过游戏主控Agent协调嫌疑人对话Agent
   */
  async chatWithSuspect(request: ChatRequest): Promise<GameAgentResponse> {
    try {
      console.log('💬 通过游戏主控Agent处理嫌疑人对话:', request);

      const agent = this.client.getAgent('gameMasterAgent');
      const result = await agent.generateVNext({
        messages: [
          {
            role: 'user',
            content: `请协调嫌疑人对话Agent处理以下对话请求：

            会话信息：
            - 游戏会话ID：${request.sessionId}
            - 嫌疑人ID：${request.suspectId}
            - 玩家问题：${request.question}
            - 对话历史：${JSON.stringify(request.conversationHistory || [])}

            请使用 game-master 工具执行 coordinate_agents 操作，目标Agent为嫌疑人对话Agent。`
          }
        ]
      });

      console.log('🤖 嫌疑人对话响应:', result);
      
      if (result.toolResults && result.toolResults.length > 0) {
        const toolResult = result.toolResults[0];
        if (toolResult.payload?.result) {
          const chatData = toolResult.payload.result;
          return {
            success: chatData.success || true,
            data: chatData.data,
            message: chatData.message || '对话成功',
            agentResponse: result.text
          };
        }
      }

      return {
        success: false,
        message: '对话失败：Agent未返回有效结果',
        error: 'NO_TOOL_CALLS',
        agentResponse: result.text
      };

    } catch (error) {
      console.error('❌ 对话失败:', error);
      return {
        success: false,
        message: `对话失败: ${error instanceof Error ? error.message : '未知错误'}`,
        error: 'CLIENT_ERROR'
      };
    }
  }

  /**
   * 提交推理结果
   * 通过游戏主控Agent协调评估Agent
   */
  async submitDeduction(submission: DeductionSubmission): Promise<GameAgentResponse> {
    try {
      console.log('🔍 通过游戏主控Agent提交推理结果:', submission);

      const agent = this.client.getAgent('gameMasterAgent');
      const result = await agent.generateVNext({
        messages: [
          {
            role: 'user',
            content: `请协调评估Agent处理以下推理提交：

            推理信息：
            - 游戏会话ID：${submission.sessionId}
            - 选择的真凶：${submission.culpritId}
            - 推理过程：${submission.reasoning}
            - 支持证据：${submission.evidence.join(', ')}
            - 信心程度：${submission.confidence}%

            请使用 game-master 工具执行 coordinate_agents 操作，目标Agent为评估Agent。`
          }
        ]
      });

      console.log('🤖 推理评估响应:', result);
      
      if (result.toolResults && result.toolResults.length > 0) {
        const toolResult = result.toolResults[0];
        if (toolResult.payload?.result) {
          const evaluationData = toolResult.payload.result;
          return {
            success: evaluationData.success || true,
            data: evaluationData.data,
            message: evaluationData.message || '推理评估完成',
            agentResponse: result.text
          };
        }
      }

      return {
        success: false,
        message: '推理评估失败：Agent未返回有效结果',
        error: 'NO_TOOL_CALLS',
        agentResponse: result.text
      };

    } catch (error) {
      console.error('❌ 提交推理失败:', error);
      return {
        success: false,
        message: `提交推理失败: ${error instanceof Error ? error.message : '未知错误'}`,
        error: 'CLIENT_ERROR'
      };
    }
  }

  /**
   * 获取游戏状态
   */
  async getGameStatus(sessionId: string): Promise<GameAgentResponse> {
    try {
      console.log('📊 获取游戏状态:', sessionId);

      const agent = this.client.getAgent('gameMasterAgent');
      const result = await agent.generateVNext({
        messages: [
          {
            role: 'user',
            content: `请获取游戏会话状态：

            会话ID：${sessionId}

            请使用 game-master 工具执行 get_status 操作。`
          }
        ]
      });

      console.log('🤖 状态查询响应:', result);
      
      if (result.toolResults && result.toolResults.length > 0) {
        const toolResult = result.toolResults[0];
        if (toolResult.payload?.result) {
          const statusData = toolResult.payload.result;
          return {
            success: statusData.success || true,
            data: statusData.data,
            gameState: statusData.gameState,
            message: statusData.message || '状态获取成功',
            agentResponse: result.text
          };
        }
      }

      return {
        success: false,
        message: '获取状态失败：Agent未返回有效结果',
        error: 'NO_TOOL_CALLS',
        agentResponse: result.text
      };

    } catch (error) {
      console.error('❌ 获取游戏状态失败:', error);
      return {
        success: false,
        message: `获取状态失败: ${error instanceof Error ? error.message : '未知错误'}`,
        error: 'CLIENT_ERROR'
      };
    }
  }

  /**
   * 暂停游戏
   */
  async pauseGame(sessionId: string): Promise<GameAgentResponse> {
    return this.manageGameSession(sessionId, 'pause_game', {});
  }

  /**
   * 恢复游戏
   */
  async resumeGame(sessionId: string): Promise<GameAgentResponse> {
    return this.manageGameSession(sessionId, 'resume_game', {});
  }

  /**
   * 结束游戏
   */
  async endGame(sessionId: string): Promise<GameAgentResponse> {
    return this.manageGameSession(sessionId, 'end_game', {});
  }

  /**
   * 管理游戏会话的通用方法
   */
  private async manageGameSession(sessionId: string, action: string, data: any): Promise<GameAgentResponse> {
    try {
      const agent = this.client.getAgent('gameMasterAgent');
      const result = await agent.generateVNext({
        messages: [
          {
            role: 'user',
            content: `请管理游戏会话：

            会话ID：${sessionId}
            操作：${action}
            数据：${JSON.stringify(data)}

            请使用 game-master 工具执行 manage_session 操作。`
          }
        ]
      });

      if (result.toolResults && result.toolResults.length > 0) {
        const toolResult = result.toolResults[0];
        if (toolResult.payload?.result) {
          const sessionData = toolResult.payload.result;
          return {
            success: sessionData.success || true,
            data: sessionData.data,
            gameState: sessionData.gameState,
            sessionInfo: sessionData.sessionInfo,
            message: sessionData.message || '会话管理成功',
            agentResponse: result.text
          };
        }
      }

      return {
        success: false,
        message: '会话管理失败：Agent未返回有效结果',
        error: 'NO_TOOL_CALLS',
        agentResponse: result.text
      };

    } catch (error) {
      console.error('❌ 会话管理失败:', error);
      return {
        success: false,
        message: `会话管理失败: ${error instanceof Error ? error.message : '未知错误'}`,
        error: 'CLIENT_ERROR'
      };
    }
  }
}

/**
 * 默认的游戏客户端实例
 */
export const gameClient = new CyberDetectiveGameClient();

/**
 * 创建游戏客户端实例的工厂函数
 */
export function createGameClient(config?: Partial<typeof MASTRA_CONFIG>) {
  const client = new MastraClient({ ...MASTRA_CONFIG, ...config });
  return new CyberDetectiveGameClient(client);
}
